package com.yu.demo.user.application.converter;

import com.yu.demo.user.application.dto.CreateUserRequest;
import com.yu.demo.user.application.dto.UpdateUserRequest;
import com.yu.demo.user.application.dto.UserResponse;
import com.yu.demo.user.domain.entity.User;
import com.yu.demo.user.domain.valueobject.*;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户转换器
 * 负责领域对象和DTO之间的转换
 */
@Component
public class UserConverter {
    
    /**
     * 创建请求DTO转换为领域实体
     */
    public User toDomain(CreateUserRequest request) {
        return User.create(
            new Username(request.getUsername()),
            new Email(request.getEmail()),
            new PasswordHash(hashPassword(request.getPassword())),
            new UserRole(request.getRole())
        );
    }
    
    /**
     * 领域实体转换为响应DTO
     */
    public UserResponse toResponse(User user) {
        UserResponse response = new UserResponse();
        response.setId(user.getId().getValue());
        response.setUsername(user.getUsername().getValue());
        response.setEmail(user.getEmail().getValue());
        response.setRole(user.getRole().getValue());
        response.setActive(user.isActiveUser());
        response.setCreatedAt(user.getCreatedAt());
        response.setUpdatedAt(user.getUpdatedAt());
        response.setLastLogin(user.getLastLogin());
        return response;
    }
    
    /**
     * 更新请求DTO转换为领域实体更新操作
     */
    public void updateDomain(User user, UpdateUserRequest request) {
        Username username = request.getUsername() != null ? 
            new Username(request.getUsername()) : null;
        Email email = request.getEmail() != null ? 
            new Email(request.getEmail()) : null;
        
        user.updateProfile(username, email);
        
        if (request.getRole() != null) {
            user.changeRole(new UserRole(request.getRole()));
        }
    }
    
    /**
     * 批量转换领域实体为响应DTO
     */
    public List<UserResponse> toResponseList(List<User> users) {
        return users.stream()
                .map(this::toResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 简单的密码哈希实现（实际项目中应使用更安全的哈希算法）
     */
    private String hashPassword(String password) {
        // 这里使用简单的哈希，实际项目中应使用BCrypt等安全哈希算法
        return String.valueOf(password.hashCode()) + "_hash";
    }
}
